package com.tools.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import com.tools.common.enums.ResultCode;
import com.tools.common.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.Objects;

@AllArgsConstructor
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常: {}, 请求地址: {}", e.getMessage(), request.getRequestURI());
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder("参数校验失败: ");

        // 收集所有参数校验错误
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append("=").append(fieldError.getDefaultMessage()).append("; ");
        }

        log.warn("{} 请求地址: {}", errorMsg, request.getRequestURI());
        return Result.fail(ResultCode.BAD_REQUEST, errorMsg.toString());
    }

    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String errorMsg = String.format("参数类型不匹配: 参数 '%s' 期望类型为 '%s', 实际值为 '%s'",
                e.getName(),
                Objects.requireNonNull(e.getRequiredType()).getSimpleName(),
                e.getValue());

        log.warn("{} 请求地址: {}", errorMsg, request.getRequestURI());
        return Result.fail(ResultCode.BAD_REQUEST, errorMsg);
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        // 记录详细错误日志
        log.error("系统异常: 请求地址: {}", request.getRequestURI(), e);
        // 返回通用错误信息，避免暴露敏感信息
        return Result.fail(ResultCode.INTERNAL_SERVER_ERROR, "系统繁忙，请稍后再试");
    }

    /**
     * 处理未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    public Result<Void> handleNotLoginException(NotLoginException e) {
        log.warn("未登录异常: {}", e.getMessage());
        return Result.fail(ResultCode.UNAUTHORIZED, "请先登录");
    }

    /**
     * 处理无权限异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public Result<Void> handleNotPermissionException(NotPermissionException e) {
        log.warn("无权限异常: {}", e.getMessage());
        return Result.fail(ResultCode.FORBIDDEN, "没有操作权限");
    }

    /**
     * 处理无角色异常
     */
    @ExceptionHandler(NotRoleException.class)
    public Result<Void> handleNotRoleException(NotRoleException e) {
        log.warn("无角色异常: {}", e.getMessage());
        return Result.fail(ResultCode.FORBIDDEN, "没有访问角色");
    }

    @ExceptionHandler(SaTokenException.class)
    public Result<Void> handleSaTokenException(SaTokenException e, HttpServletRequest request) {
        log.warn("权限认证异常: {}, 请求地址: {}", e.getMessage(), request.getRequestURI());
        return Result.fail(ResultCode.FORBIDDEN, "权限认证失败：" + e.getMessage());
    }

    @ExceptionHandler(WorkflowException.class)
    public Result<Void> handleWorkflowException(WorkflowException e) {
        log.warn("工作流程异常: {}, ", e.getMessage());
        return Result.fail(ResultCode.WORKFLOW_ERROR, e.getMessage());
    }


}
